package com.example.login;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.StringUtils;
import com.example.dao.ClientInfoDao;
import com.example.entity.ClientInfoEntity;
import com.example.login.username.UsernameAuthentication;
import com.example.model.api.Result;
import com.example.security.InfoDetail;
import com.example.utils.Cookies;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 认证成功/登录成功 事件处理器
 */
@Component
@Slf4j
public class UsernamePasswordLoginSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler implements AuthenticationSuccessHandler {


    @Autowired
    private OAuth2TokenService oAuth2TokenService;

    @Autowired
    private ClientInfoDao clientInfoDao;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        // 清除 session 中的错误信息
        HttpSession session = request.getSession();
        session.removeAttribute("loginError");
        // 获取当前用户信息
        UsernameAuthentication usernameAuthentication = (UsernameAuthentication) authentication;
        String password = usernameAuthentication.getPassword();
        String username = usernameAuthentication.getUsername();
        InfoDetail infoDetail = usernameAuthentication.getInfoDetail();
        infoDetail.setUsername(username);
        infoDetail.setPassword(password);
        List<ClientInfoEntity> clientInfo = clientInfoDao.findClientInfo(infoDetail.getStoreId());
        ClientInfoEntity clientInfoEntity = clientInfo.get(0);
        String scopes = clientInfoEntity.getScopes().replace(",", " ");
        infoDetail.setScopes(scopes);
        infoDetail.setClientId(clientInfoEntity.getClientId());
        infoDetail.setClientSecret(clientInfoEntity.getClientSecret());
        Map mapResult = oAuth2TokenService.generateAccessToken(infoDetail);
        log.info("登录认证成功 {} {}", new Date(), MapUtil.isNotEmpty(mapResult));

        String postLogoutRedirectUris = clientInfoEntity.getPostLogoutRedirectUris();
        String access_token = (String) mapResult.get("access_token");
        Cookies.sendRedirectCookies(response, access_token, postLogoutRedirectUris);
    }
}
